package ssq.gamest.toolchain;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;

import ssq.utils.DirUtils;
import fri.patterns.interpreter.parsergenerator.Parser;
import fri.patterns.interpreter.parsergenerator.Token;
import fri.patterns.interpreter.parsergenerator.builder.SerializedParser;
import fri.patterns.interpreter.parsergenerator.semantics.ReflectSemantic;

public class AIWeightExpression extends ReflectSemantic
{
    Parser                    parser;

    private static String[][] rules = {
        { "DONE", "EXPRESSION" },
        { "EXPRESSION", "TERM" },
        { "EXPRESSION", "EXPRESSION", "'+'", "TERM" },
        { "EXPRESSION", "EXPRESSION", "'-'", "TERM" },
        { "TERM", "FACTOR", },
        { "TERM", "TERM", "'*'", "FACTOR" },
        { "TERM", "TERM", "'/'", "FACTOR" },
        { "FACTOR", "`float`" },
        { "FACTOR", "\"sum\"" },
        { "FACTOR", "\"hands\"" },
        { "FACTOR", "\"residual\"" },
        { "FACTOR", "'-'", "FACTOR" },
        { "FACTOR", "'('", "EXPRESSION", "')'" },
        { Token.IGNORED, "`whitespaces`" },
    };

    public Object DONE(Object EXPRESSION)
    {
        return true;
    }

    boolean test(String expr)
    {
        try
        {
            parser.setInput(expr);

            if (parser.parse(this))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (IOException e)
        {
            return false;
        }
    }

    public AIWeightExpression() throws Exception
    {
        iniParser();
    }

    protected Parser iniParser() throws Exception
    {
        // read the syntax from EBNF file
        parser = new SerializedParser().get(null, rules, "AIWeight");

        File dump = new File(DirUtils.getTmpRoot() + "parsers/AIWeight.dump.txt");
        if (!dump.exists())
        {
            parser.getParserTables().dump(new PrintStream(dump));
        }

        return parser;
    }
}